package net.cmkj.mine.core.admin.login;

import com.jfinal.aop.Clear;
import net.cmkj.mine.bean.SysDept;
import net.cmkj.mine.bean.SysUser;
import net.cmkj.mine.common.controller.BaseController;
import net.cmkj.mine.common.model.InvokeResult;
import net.cmkj.mine.interceptor.AuthorityInterceptor;
import net.cmkj.mine.util.CommonUtils;
import net.cmkj.mine.util.CookieUtils;
import net.cmkj.mine.util.IWebUtils;
import net.cmkj.mine.util.MyDigestUtils;

import java.util.ArrayList;
import java.util.List;

public class LoginController extends BaseController {
	
	@Clear(AuthorityInterceptor.class)
	public void index() {
		SysUser user = IWebUtils.getCurrentSysUser(getRequest());
		if (user != null) {
			String deptids = user.getDeptids();
			if (deptids != null && !"".equals(deptids)) {
				String[] dids = deptids.split(",");
				List<SysDept> depts = new ArrayList<>();
				for (String deptId : dids) {
					SysDept dept = SysDept.dao.findById(deptId);
					depts.add(dept);
				}
				setAttr("selectDept", CookieUtils.getCookieByName(getRequest(), "user_dept"));
				setAttr("depts", depts);
			}
			render("main/main.html");
		} else {
			render("login.html");
		}
	}
	
	@Clear(AuthorityInterceptor.class)
	public void gologin() {
		SysUser user = IWebUtils.getCurrentSysUser(getRequest());
		if (user != null) {
			String deptids = user.getDeptids();
			if (deptids != null && !"".equals(deptids)) {
				String[] dids = deptids.split(",");
				List<SysDept> depts = new ArrayList<>();
				for (String deptId : dids) {
					SysDept dept = SysDept.dao.findById(deptId);
					depts.add(dept);
				}
				setAttr("selectDept", CookieUtils.getCookieByName(getRequest(), "user_dept"));
				setAttr("depts", depts);
			}
			render("main/main.html");
		} else {
			render("login.html");
		}
	}
	
	@Clear(AuthorityInterceptor.class)
	public void dologin() {
		SysUser user = SysUser.dao.getByName(getPara("username"));
		if (user == null) {
			renderJson(InvokeResult.failure("用户不存在！"));
			return;
		}
		if(!user.getPwd().equals(MyDigestUtils.hash(MyDigestUtils.hash(this.getPara("password"))))){
			renderJson(InvokeResult.failure("用户密码输入有误!"));
			return;
		}
		if(user.getInt("status")==2){
			renderJson(InvokeResult.failure("用户被冻结，请联系管理员!"));
			return;
		}
		Integer autoLogin = getParaToInt("autoLogin", 0);
		String deptids = user.getDeptids();
		if (deptids != null && !"".equals(deptids)) {
			String[] dids = deptids.split(",");
			CookieUtils.addCookie(getResponse(), "user_dept", dids[0], 60*60*24*30);
			user.setDeptid(CommonUtils.converInteger(dids[0]));
		}
		IWebUtils.setCurrentLoginSysUser(getResponse(), getSession(), user, autoLogin);
		renderJson(InvokeResult.success());
	}
	
	public void logout() {
		IWebUtils.removeCurrentSysUser(getRequest(), getResponse());
		render("login.html");
	}
	
	public void dologout() {
		render("login.html");
	}

}
